<template>
  <a-modal
    :visible="visible"
    okText="提交"
    cancelText="关闭"
    :title="title"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    width="800px"
    @cancel="closeModal()"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
      <a-form-item label="收货人">
        <a-input
          :maxLength="50"
          v-decorator="[
            'userName',
            { 
              rules: [
                { required: true, message: '请填写收货人名称' },
                {
                  validator: handleEmpty,
                  message: '请填写收货人名称',
                },
              ] 
            },
          ]"
          placeholder="请填写收货人名称"
        />
      </a-form-item>
      <a-form-item
        label="联系电话"
        help="支持输入手机号或者座机号码，座机格式例如：xxxx-xxxxxxxx"
      >
        <a-input
          :maxLength="13"
          type="tel"
          v-decorator="[
            'userPhone',
            {
              rules: [
                { required: true, message: '请填写联系电话' },
                {
                  pattern: /^((\d{3,4}-\d{7,8})|(1[3,4,5,6,7,8,9]\d{9}))$/,
                  message: '请填写正确的联系电话',
                },
              ],
            },
          ]"
          placeholder="请填写联系电话"
        />
      </a-form-item>
      <a-form-item label="所在区域" :help="addressHelp">
        <a-cascader
          :field-names="{
            label: 'areaName',
            value: 'id',
            children: 'children',
          }"
          :options="areaTree"
          :show-search="true"
          placeholder="请选择所属区域"
          v-decorator="[
            'areaIdList',
            { rules: [
              { required: true, message: '请选择所属区域' },
              {
                  validator: handleEmpty,
                  message: '请选择所属区域',
                },
            ] },
          ]"
        />
      </a-form-item>
      <a-form-item label="详细地址">
        <a-textarea
          :maxLength="100"
          v-decorator="[
            'detailAddress',
            { rules: [
              { required: true, message: '请填写详细地址' },
              {
                  validator: handleEmpty,
                  message: '请填写详细地址',
                },
            ] },
          ]"
          placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { getAreaTree } from "@/utils/asyncUtils";
import { treeFindPath } from "@/utils";
import zip from "lodash/zip";
export default {
  name: "address-info",
  props: {
    record: {
      type: Object,
      default() {
        return {};
      },
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    title() {
      return "修改地址";
    },
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: "coordinated" }),
      areaTree: [],
      confirmLoading: false,
      addressHelp: "正在获取地区信息，请稍等...",
      defaultArea:[],
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (!(this.areaTree && this.areaTree.length)) {
          this.addressHelp = "正在获取地区信息，请稍等...";
          getAreaTree().then((res) => {
            console.log('areaTree',res)
            // res.forEach(item1=>{
            //   //console.log(item1.children && Array.isArray(item1.children))
            //   if(item1.children && Array.isArray(item1.children)){
            //     item1.children.forEach(item2=>{
            //       //console.log(item2);
            //       if(item2.children && Array.isArray(item2.children)){
            //         item2.children.forEach(item3=>{
            //           if(item3.children){
            //             item3.children=null;
            //           }
            //         })
            //       }
            //     })
            //   }
            // })
            this.areaTree = res;
            this.addressHelp = "";
          });
        }
        
        if (this.record.id) {
          console.log(this.record, "this.record.areaIdList");
          this.record.areaIdList = [
            this.record.provinceCode,
            this.record.cityCode,
            this.record.districtCode,
            this.record.streetCode || ''
          ].filter((item) => item);
          console.log(this.record.areaIdList, "this.record.areaIdList");

          this.$nextTick(() => {
            const formItems = this.form.getFieldsValue();
            // 获取表单控件 对象
            console.log('formItems',formItems);
            // 将查询到的record 里的值赋值给我表单控件 对象的值
            Object.keys(formItems).forEach((key) => {
              formItems[key] = this.record[key];
              console.log(formItems)
            });
            formItems.areaIdList=this.record.areaIdList || [];
            // 重新赋值 设置表单控件
            this.form.setFieldsValue(formItems);
            // console.log('formItems',formItems);
          });
        }
      }
    },
  },
  mounted() {},
  methods: {
    handleEmpty(rule,value,callback){
      console.log('value',value)
      try{
        if(/^\s*$/g.test(value)){
          throw new Error('请输入')
        }
      }
      catch(err){
        callback(err);
      }
      callback();
    },
    getAreaSubmitInfo(areaIdList = []) {
      const lastId = areaIdList[areaIdList.length - 1];
      const areaNameList = treeFindPath(
        this.areaTree,
        (data) => lastId == data.id,
        [],
        "areaName"
      );
      const areaList = zip(areaIdList, areaNameList); // 返回 [[省id, 省name], [市id, 市name], [区id, 区name], [街道id, 街道name]]
      // const areaInfo = {
      //   provinceCode: (areaList[0] && areaList[0][0]) || "",
      //   province: (areaList[0] && areaList[0][1]) || "",
      //   cityCode: (areaList[1] && areaList[1][0]) || "",
      //   city: (areaList[1] && areaList[1][1]) || "",
      //   areaCode: (areaList[2] && areaList[2][0]) || "",
      //   area: (areaList[2] && areaList[2][1]) || "",
      //   streetCode: (areaList[3] && areaList[3][0]) || "",
      //   street: (areaList[3] && areaList[3][1]) || "",
      //   treePath: `0,${areaIdList.join(",")}`,
      // };
      const areaInfo = {
        provinceCode: (areaList[0] && areaList[0][0]) || "",
        provinceName: (areaList[0] && areaList[0][1]) || "",
        cityCode: (areaList[1] && areaList[1][0]) || "",
        cityName: (areaList[1] && areaList[1][1]) || "",
        districtCode: (areaList[2] && areaList[2][0]) || "",
        districtName: (areaList[2] && areaList[2][1]) || "",
        streetCode: (areaList[3] && areaList[3][0]) || "",
        streetName: (areaList[3] && areaList[3][1]) || "",
        // treePath: `0,${areaIdList.join(",")}`,
      };

      return areaInfo;
    },

    handleSubmit() {
      this.confirmLoading = true;
      this.form.validateFields((err, values) => {
        if (!err) {
          //let url = "/address/config/add";
          console.log(this.record);
          if (this.record.id) {
            let url = "/order/goods/update/adress";
            const areaInfo = this.getAreaSubmitInfo(values.areaIdList);
            console.log('areaIdList',values,values.areaIdList);
            if(!areaInfo.provinceName || !areaInfo.cityName || !areaInfo.districtName){
              this.confirmLoading=false;
              this.$message.error('请选择所在区域');
              return;
            }
            console.log('areaInfo',areaInfo)
            //delete values.areaIdList;
            console.log('areaInfo.province,areaInfo.city,areaInfo.area,areaInfo.street,values.address;',areaInfo.provinceName,areaInfo.cityName,areaInfo.districtName)

            //values.detailAddress = [areaInfo.provinceName,areaInfo.cityName,areaInfo.districtName,areaInfo.streetName,values.detailAddress].filter(item=>item).join('');
            this.$post(url, { ...values, ...areaInfo, orderGoodsId: this.record.id })
              .then((res) => {
                this.confirmLoading = false;
                if (res && res.returnCode === 1000) {
                  this.$message.success("保存成功！");
                  this.closeModal(true);
                }
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          } else {
            this.confirmLoading = false;
          }
        }
        else {
          this.confirmLoading=false;
        }
      });
    },

    closeModal(freshTable) {
      this.form.resetFields();
      this.$emit("cancel", freshTable);
    },
  },
};
</script>